package jun.empdepmanagersystem02.until;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import jun.empdepmanagersystem02.pojo.QiNiuYun;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class QiniuYununtils {
    public static String upload(QiNiuYun qiNiuYun, byte[] data, String name) throws QiniuException {

        String accessKey = qiNiuYun.getAk();
        String secretKey = qiNiuYun.getSk();
        String bucket = qiNiuYun.getBucketname();
        //构造一个带指定 Region 对象的配置类

///*        机房	Region
//        华东	Region.region0(), Region.huadong()
//        华北	Region.region1(), Region.huabei()
//        华南	Region.region2(), Region.huanan()
//        北美	Region.regionNa0(), Region.beimei()
//        东南亚	Region.regionAs0(), Region.xinjiapo()*/
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//如果是Windows情况下，格式是 D:\\qiniu\\test.png
//默认不指定key的情况下，以文件内容的hash值作为文件名

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, name);
//上传三要素：文件数组 文件名 上传令牌
        Response response = uploadManager.put(data, name, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println(qiNiuYun.getUrlRoot() + putRet.key);
        return qiNiuYun.getUrlRoot() + putRet.key;
    }
}
